﻿using System;
using System.Text;
using System.Web.UI.WebControls;
using CustomerContactSystem.Core.Model;
using NHibernate.Criterion;

namespace CustomerContactSystem.WebForms.Enquiries.Customers {
    public partial class Change : BasePage {
        protected void Page_Load(object sender, EventArgs e) {
            if (!IsValidPageRequest(true, true, "id")) {
                return;
            }

            if (Request.QueryString["changeto"] != null) {
                ChangeCustomer();
            }
            else {
                EnquiryIdCaption.Text = Request.QueryString["id"];
                EnquiryIdCaption.NavigateUrl = "~/Enquiries/View.aspx?id=" + Request.QueryString["id"];
                CreateNewLink.NavigateUrl = "~/Customers/Create.aspx?" + GetQueryString();

                GetCustomer();
                SetValuesFromQueryString();
                
                if (Request.QueryString.Count > 1) {
                    SearchForm.Attributes.Add("class", "search-form collapsed");
                    FindCustomers();
                }
            }
        }

        private void ChangeCustomer() {
            var newCustomerId = int.Parse(Request.QueryString["changeto"]);
            var customer = CustomerRepository.GetById(newCustomerId);
            var enquiryId = int.Parse(Request.QueryString["id"]);
            var enquiry = EnquiryRepository.GetById(enquiryId);

            if (enquiry == null) {
                return;
            }

            enquiry.ChangeCustomer(LoggedUser.DisplayName, customer);
            EnquiryRepository.Update(enquiry);

            Response.Redirect("~/Enquiries/View.aspx?id=" + enquiry.Id);
        }

        private void GetCustomer() {
            var enquiryId = int.Parse(Request.QueryString["id"]);
            var enquiry = EnquiryRepository.GetById(enquiryId);

            if (enquiry == null || enquiry.Customer == null) {
                return;
            }

            var customer = enquiry.Customer;
            CurrentCustomer.Text = customer.FullName + ", " + customer.AddressLine;
        }

        private void SetValuesFromQueryString() {
            FirstName.Text = QueryStringOrEmpty("firstname");
            SecondName.Text = QueryStringOrEmpty("secondname");
            Address.Text = QueryStringOrEmpty("address");
        }

        private void FindCustomers() {
            var customers = CustomerRepository.QueryOver();
            if (QueryStringOrEmpty("firstname").Length > 0) {

                customers = customers.WhereRestrictionOn(c => c.FirstName).IsLike(QueryStringOrEmpty("firstname").ToLower(), MatchMode.Anywhere);
            }

            if (QueryStringOrEmpty("secondname").Length > 0) {
                customers = customers.WhereRestrictionOn(c => c.SecondName).IsLike(QueryStringOrEmpty("secondname").ToLower(), MatchMode.Anywhere);
            }

            if (QueryStringOrEmpty("address").Length > 0) {
                customers = customers.WhereRestrictionOn(c => c.Address1).IsLike(QueryStringOrEmpty("address").ToLower(), MatchMode.Anywhere);
            }

            customers = customers.OrderBy(c => c.SecondName).Asc.ThenBy(c => c.FirstName).Asc;
            
            CustomerList.DataSource = customers.List();
            CustomerList.DataBind();
        }

        protected void SearchCustomersClick(object sender, EventArgs e) {
            if (!IsValidPageRequest(true, false, "id")) {
                
            }
            Response.Redirect("~/Enquiries/Customers/Change.aspx?" + GetQueryString());
        }

        private string GetQueryString() {
            var sb = new StringBuilder();
            sb.Append("id=" + Request.QueryString["id"]);
            sb.Append("&firstname=" + FirstName.Text);
            sb.Append("&secondname=" + SecondName.Text);
            sb.Append("&address=" + Address.Text);
            return sb.ToString();
        }

        protected void CustomerListItemDataBound(object sender, RepeaterItemEventArgs e) {         
            if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem) {
                return;
            }

            var rowCustomer = (Customer)e.Item.DataItem;
            var useInCurrentEnquiryLink = (HyperLink)e.Item.FindControl("UseInCurrentEnquiryLink");

            useInCurrentEnquiryLink.NavigateUrl = "~/Enquiries/Customers/Change.aspx?id=" + Request.QueryString["id"] +
                                                  "&changeto=" + rowCustomer.Id;
        }
    }
}